package com.fxkj.cloud.drms.ui.listener;

import com.fxkj.cloud.dbs.common.constants.SyncStatus;
import com.fxkj.cloud.dbs.common.constants.WsMsgEnum;
import com.fxkj.cloud.dbs.common.event.stream.RemoteControlPlanSyncEvent;
import com.fxkj.cloud.dbs.common.model.DeviceControlOrder;
import com.fxkj.cloud.dbs.common.model.ws.ControlPlanSyncStatus;
import com.fxkj.cloud.dbs.common.model.ws.FxWsMsg;
import com.fxkj.cloud.drms.domain.mqtt.CommandAndQuerySender;
import com.fxkj.cloud.drms.domain.mqtt.DeviceControlOrderCommand;
import com.fxkj.cloud.drms.domain.ws.service.FxWsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * <p>description: 处理远程控制指令下发事件</p>
 * @author ww
 * @date 2025/3/21 16:16
 */
@Component
@Slf4j
public class RemoteControlPlanSyncListener {
    private final FxWsClient wsClient;
    private final CommandAndQuerySender commandAndQuerySender;

    public RemoteControlPlanSyncListener(FxWsClient wsClient, CommandAndQuerySender commandAndQuerySender) {
        this.wsClient = wsClient;
        this.commandAndQuerySender = commandAndQuerySender;
    }

    @Bean
    public Consumer<RemoteControlPlanSyncEvent> controlPlanSync() {
        return event -> {
            log.trace("收到远程控制指令下发事件:{}", event);
            List<DeviceControlOrder> deviceControlOrders = event.getDeviceControlOrders();
            UUID syncRequestId = event.getSyncRequestId();
            List<DeviceControlOrderCommand> deviceControlOrderCommands = new ArrayList<>();
            deviceControlOrders.forEach(order -> {
                deviceControlOrderCommands.add(new DeviceControlOrderCommand(syncRequestId, order.getDeviceSerialNo(), order.getLcNos(), order.getControlOrders()));
            });
            commandAndQuerySender.controlPlanSend(deviceControlOrderCommands);

            //推送ws消息
            UUID controlPlanId = event.getControlPlanId();

            wsClient.pushNotificationToOrganization(
                    event.getOrganizationId(),
                    new FxWsMsg<>(WsMsgEnum.CONTROL_PLAN_DEVICE_STATUS,
                            ControlPlanSyncStatus.of(controlPlanId, deviceControlOrders.stream().map(DeviceControlOrder::getDeviceId).collect(Collectors.toSet()), SyncStatus.SYNCING))
            );
        };
    }
}
